//
//  MembershipController.swift
//  home
//
//  Created by Yun Zeng on 2019/8/6.
//  Copyright © 2019 Yun Zeng. All rights reserved.
//

import UIKit

class MembershipController: UIViewController {
    
    lazy var customBarView: UserCustomBarView = {
        return UserCustomBarView()
    } ()
    
    lazy var contentsView: UIScrollView = {
        return UIScrollView()
    } ()
    
    lazy var headerView: UserHeaderInfoView = {
        return UserHeaderInfoView()
    } ()
    
    lazy var settingsView: UITableView = {
        let table = UITableView()
        return table
    } ()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initNavigationBar()
        self.view.backgroundColor = UIColor.white
        
        let containerView = UIView()
        containerView.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(containerView)
        
        containerView.addSubview(contentsView)
        contentsView.addSubview(headerView)
        contentsView.addSubview(settingsView)
        
        containerView.addSubview(customBarView)
        
        containerView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
        containerView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
        containerView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
        containerView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
        
        contentsView.translatesAutoresizingMaskIntoConstraints = false
        contentsView.showsVerticalScrollIndicator = false
        contentsView.alwaysBounceVertical = true
        
        contentsView.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
        contentsView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor).isActive = true
        contentsView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true
        contentsView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true
        
        self.customBarView.translatesAutoresizingMaskIntoConstraints = false
        self.customBarView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
        self.customBarView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
        self.customBarView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
        self.customBarView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
        
        headerView.translatesAutoresizingMaskIntoConstraints = false
        headerView.topAnchor.constraint(equalTo: contentsView.topAnchor).isActive = true
        headerView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true
        headerView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true
        headerView.heightAnchor.constraint(equalToConstant: 65).isActive = true
        
        headerView.account = "18565381403"
        headerView.name = "了结大师"
        customBarView.title = "了结大师"
        
        // 设置单元格
        settingsView.translatesAutoresizingMaskIntoConstraints = false
        settingsView.topAnchor.constraint(equalTo: headerView.bottomAnchor, constant: 8).isActive = true
        settingsView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 15).isActive = true
        settingsView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -15).isActive = true
        
        settingsView.isScrollEnabled = false
        settingsView.register(UserSettingCell.self, forCellReuseIdentifier: UserSettingCell.identifier)
        settingsView.register(UITableViewHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: "SettingViewHeaderFooterView")
        settingsView.rowHeight = 54
                
        settingsView.indicatorStyle = .black
        settingsView.delegate = self
        settingsView.sectionFooterHeight = 8.0
        settingsView.sectionHeaderHeight = 8.0
        settingsView.dataSource = self
        settingsView.separatorStyle = .none
        settingsView.backgroundColor = UIColor(red: 242/255, green: 242/255, blue: 242/255, alpha: 1)
        
        settingsView.heightAnchor.constraint(equalToConstant: 6 * 54 + 16 * 4 + 8).isActive = true
    }
}

extension MembershipController: UIScrollViewDelegate {
    func initNavigationBar() {
        self.contentsView.delegate = self
        let navigationBar = self.navigationController!.navigationBar
        navigationBar.setBackgroundImage(UIImage(), for: .default)
        navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.clear]
        navigationBar.shadowImage = UIImage()
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        var offset: CGFloat = (scrollView.contentOffset.y + 74) / 40
         if offset > 2 {
             offset = 2
         } else if offset < 0 {
             offset = 0
         }
         self.customBarView.opacity = Float(offset)
    }
}
 
fileprivate struct HomeSetting {
    var type: HomeSettingType
    var icon: String
    var title: String

    enum HomeSettingType: Int {
        case userHome
        case userMessage
        case userFavorites
        case userSetting
        case userLife
        case userFeedback
    }
    
    static let settings = [
        [
            HomeSetting(type: .userHome, icon: "user-settings-home", title: "家庭管理"),
            HomeSetting(type: .userMessage, icon: "user-message", title: "消息通知"),
            HomeSetting(type: .userFavorites, icon: "user-settings-favorites", title: "Widget小工具"),
            HomeSetting(type: .userSetting, icon: "user-settings-common", title: "设置"),
        ],[
            HomeSetting(type: .userLife, icon: "user-life-studio", title: "美好生活研究所"),
            HomeSetting(type: .userFeedback, icon: "user-feedback", title: "意见反馈"),
        ]
    ]
}

extension MembershipController: UITableViewDelegate, UITableViewDataSource {
   func numberOfSections(in tableView: UITableView) -> Int {
        return HomeSetting.settings.count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let setting = HomeSetting.settings[indexPath.section][indexPath.row]
        var controller: UIViewController
        
        switch setting.type {
        case .userHome:
            controller = UserHomeController()
        case .userMessage:
            controller = UserMessageController()
        case .userFavorites:
            controller = UserFavoritesController()
        case .userLife:
            controller = UserLifeController()
        case .userFeedback:
            controller = UserFeedbackController()
        case .userSetting:
            controller = UserSettingsController()
        }
        
        controller.modalPresentationStyle = .automatic
        controller.isModalInPresentation = false
        self.navigationController?.present(controller, animated: true)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return HomeSetting.settings[section].count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: UserSettingCell.identifier, for: indexPath) as! UserSettingCell
        let setting = HomeSetting.settings[indexPath.section][indexPath.row]
        cell.settingView.title = setting.title
        cell.settingView.icon = setting.icon
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 16
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 20
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let cell = tableView.dequeueReusableHeaderFooterView(withIdentifier: "SettingViewHeaderFooterView")!
        let view = UIView()
        cell.contentView.addSubview(view)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.leadingAnchor.constraint(equalTo: cell.leadingAnchor).isActive = true
        view.trailingAnchor.constraint(equalTo: cell.trailingAnchor).isActive = true
        view.topAnchor.constraint(equalTo: cell.topAnchor, constant: -8).isActive = true
        view.heightAnchor.constraint(equalToConstant: 16).isActive = true
        view.backgroundColor = UIColor(red: 242/255, green: 242/255, blue: 242/255, alpha: 1)
        view.layer.cornerRadius = 8
        cell.layer.masksToBounds = true
        cell.clipsToBounds = true
        cell.contentView.backgroundColor = UIColor.clear
        cell.backgroundView = UIView()
        cell.backgroundView?.backgroundColor = UIColor.white
         return cell
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let cell = tableView.dequeueReusableHeaderFooterView(withIdentifier: "SettingViewHeaderFooterView")!
        let view = UIView()
        cell.contentView.addSubview(view)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.leadingAnchor.constraint(equalTo: cell.leadingAnchor).isActive = true
        view.trailingAnchor.constraint(equalTo: cell.trailingAnchor).isActive = true
        view.topAnchor.constraint(equalTo: cell.topAnchor, constant: 8).isActive = true
        view.heightAnchor.constraint(equalToConstant: 16).isActive = true
        view.backgroundColor = UIColor(red: 242/255, green: 242/255, blue: 242/255, alpha: 1)
        view.layer.cornerRadius = 8
        view.clipsToBounds = true
        view.layer.masksToBounds = true
        cell.layer.masksToBounds = true
        cell.clipsToBounds = true
        cell.backgroundView = UIView()
        cell.backgroundView?.backgroundColor = UIColor.white
        return cell
    }

}

// MARK: - 用户表头信息
@IBDesignable class UserHeaderInfoView: UIView {
    @IBInspectable var head: UIImage? {
        didSet {
            self.headImage.image = head
        }
    }
    
    @IBInspectable var name: String = "" {
        didSet {
            let attributes: [NSAttributedString.Key : Any] = [
                NSAttributedString.Key.font: UIFont.systemFont(ofSize: 24, weight: UIFont.Weight.medium),
                NSAttributedString.Key.foregroundColor: UIColor(red: 0, green: 0, blue: 0, alpha: 1),
                NSAttributedString.Key.kern: 0.41]
            self.nameLabel.attributedText = NSAttributedString(string: name, attributes: attributes)
        }
    }
    
    @IBInspectable var account: String = "" {
        didSet {
            let attributes: [NSAttributedString.Key : Any] = [
                NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.medium),
                NSAttributedString.Key.foregroundColor: UIColor(hex: "626262"),
                NSAttributedString.Key.kern: 0.24]
            self.accountLabel.attributedText = NSAttributedString(string: "账号: " + account, attributes: attributes)
        }
    }
    
    private lazy var headImage: UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "user-head")
        return view
    }()
    
    private lazy var nameLabel: UILabel = {
        let label = UILabel()
        return label
    }()
    
    private lazy var accountLabel: UILabel = {
        let label = UILabel()
        return label
    }()
    
    func initialize() {
        self.addSubview(headImage)
        self.addSubview(nameLabel)
        self.addSubview(accountLabel)
        
        headImage.translatesAutoresizingMaskIntoConstraints = false
        headImage.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20).isActive = true
        headImage.topAnchor.constraint(equalTo: topAnchor).isActive = true
        headImage.widthAnchor.constraint(equalToConstant: 56.0).isActive = true
        headImage.heightAnchor.constraint(equalToConstant: 56.0).isActive = true
        headImage.clipsToBounds = true
        headImage.layer.cornerRadius = 12
        
        nameLabel.translatesAutoresizingMaskIntoConstraints = false
        nameLabel.leadingAnchor.constraint(equalTo: headImage.trailingAnchor, constant: 12).isActive = true
        nameLabel.topAnchor.constraint(equalTo: headImage.topAnchor, constant: -5).isActive = true
        nameLabel.heightAnchor.constraint(equalToConstant: 40).isActive = true
        nameLabel.autoresizingMask = .flexibleWidth
        
        accountLabel.translatesAutoresizingMaskIntoConstraints = false
        accountLabel.leadingAnchor.constraint(equalTo: headImage.trailingAnchor, constant: 13).isActive = true
        accountLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 0).isActive = true
        accountLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true
        accountLabel.autoresizingMask = .flexibleWidth
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        initialize()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initialize()
    }
}

